package cn.template.services;

import cn.template.models.common.JwtUser;
import cn.template.models.User;
import cn.template.models.UserRepository;
import cn.template.models.exceptions.DatabaseOperationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<UserRepository, User> {
    private static final PasswordEncoder passwordEncoder =  new BCryptPasswordEncoder();;

    public UserService(UserRepository repository) {
        this.setRepository(repository);
    }

    public Page<User> getByName(int page, int size, long companyId, String name) {
        try {
            UserRepository repository = this.getRepository();
            return name  == null || name.isEmpty() ?
                    repository.findAllByCompany(companyId, this.getPageable(page, size)) :
                    repository.findAllByCompanyAndName(companyId, name, this.getPageable(page, size, "name", Sort.Direction.ASC));
        } catch (RuntimeException ex) {
            throw new DatabaseOperationException("Fail to query user by company and name", ex);
        }
    }

    public JwtUser getByUsername(String username) {
        try {
            User u = this.getRepository().getByUsername(username);

            return null == u ? null : new JwtUser(u);
        } catch (RuntimeException ex) {
            throw new DatabaseOperationException("Fail to query user by username: " + username, ex);
        }
    }

    public static String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    public static PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }
}
